<?php
namespace ac\modules\company\controllers;

use Yii;
use ac\controllers\AuthController;
use app\modules\company\models\Company;
use app\modules\company\models\CompanySearch;
use app\modules\company\models\CompanyWechat;
use app\models\Admin;
use app\models\CompanyAccountRecord;
use common\component\exception\ErrMap;
use common\component\tool\Tool;
use common\models\OperationLog;


class CompanyController extends AuthController
{

	/*企业列表*/
    public function actionCompanyList()
    {
        if(isset($this->get['page'])){
            $currPage = intval($this->get['page']?$this->get['page']:1);
        }else{
            $currPage = 1;
        }
        $pageSize = Tool::getPageSize();

        $Search = (new CompanySearch())->search($this->get);
        if($Search === false){//验证搜索参数不通过
            $count = 0;
            $companyList = array();
        }else{
            $count = $Search->count();
            $companyList = $Search->select(['com_id', 'company_name', 'business_license', 'province', 'city', 'comid', 'contacts', 'phones', 'account', 'level', 'state', 'add_time'])
                                  ->with('province')
                                  ->with('city')
                                  ->offset($pageSize*($currPage-1))->limit($pageSize)
                                  ->orderBy(['add_time' => SORT_DESC])
                                  ->asArray()->all();
        }
        $res = array(
            'list' => $companyList,
            'pageInfo' => array(
                'count' => intval($count),
                'currPage' => $currPage,
                'pageSize' => $pageSize,
            ),
        );
        return Tool::showRes([0, '获取成功'], $res);
    }

    /*添加企业*/
    public function actionAddCompany()
    {
        if(Yii::$app->request->isPost){
            // P($this->post);
            $transaction = Yii::$app->db->beginTransaction();//事物处理
            $pass = true;
            try{
                // P($this->session->get('loginInfo')->userInfo['com_id']);
                /*添加企业信息*/
                $company = new Company;
                $this->checkContact();
                $this->post['Company']['recommend'] = $this->session->get('loginInfo')->userInfo['com_id'];//推荐企业ID
                if(!($comid = $company->addCompany($this->post))){
                    if($company->hasErrors()){
                        $backInfo = ErrMap::getError(10005);//返回信息
                        $exception = $company->getErrors();//异常信息
                    }
                    $pass = false;
                }

                if($pass){
                    /*添加超级管理员*/
                    $Admin = new Admin;
                    $this->post['Admin']['comid'] = $comid;
                    $this->post['Admin']['issuper'] = 1;
                    if(!$Admin->addAdmin($this->post)){
                        if($Admin->hasErrors()){
                            $backInfo = ErrMap::getError(10005);//返回信息
                            $exception = $Admin->getErrors();//异常信息
                            if(array_key_exists("repeatUsername", $exception)){
                                $backInfo = ErrMap::getError(10011);//返回信息
                            };
                        }
                        $pass = false;
                    }
                }

                if($pass){
                    $backInfo = [0, '添加企业成功'];//返回信息
                    $transaction->commit();
                }
            }catch(\Exception $exception){
                $transaction->rollback();
            };
        };

        if(!isset($backInfo)){
            $backInfo = ErrMap::getError(10005);//返回信息
        }
        if(!isset($exception)){
            $exception = '';//异常信息
        }
        //操作日志
        if(gettype( $res = OperationLog::addLog($this->operationLogArgs($backInfo), $exception) ) != 'boolean'){
            return $res;
        };
    }

    /*
    修改企业
    */
    public function actionModifyCompany()
    {
        /*如果有数据，进行修改*/
        if(Yii::$app->request->isPost and
            isset($this->post['Company']['comid']) and
            $this->checkComID($this->post['Company']['comid'])){
            $id = $this->post['Company']['comid'];
            if(!$id){
                $backInfo = ErrMap::getError(10005);//返回信息
            }else{
                $company = new Company;
                $this->checkContact();
                if($company->modifyCompany($this->post, $id)){
                    $backInfo = [0, $this->post['Company']['company_name'] . '修改信息成功'];//返回信息
                }else{
                    if($company->hasErrors()){
                        $backInfo = ErrMap::getError(10005);//返回信息
                        $exception = $company->getErrors();//异常信息
                    }
                }
            }

            if(!isset($backInfo)){
                $backInfo = ErrMap::getError(10005);//返回信息
            }
            if(!isset($exception)){
                $exception = '';//异常信息
            }
            //操作日志
            if(gettype( $res = OperationLog::addLog($this->operationLogArgs($backInfo), $exception) ) != 'boolean'){
                return $res;
            };

        }

        /*取出单个数据*/
        if(Yii::$app->request->isGet){
            $id = isset($this->get['id'])?$this->get['id']:'';
            if($id){
                $company = Company::find()
                           ->select(['company_name', 'company_profile', 'business_license', 'country', 'province', 'city', 'district', 'address', 'zipcode', 'comid', 'contacts', 'phones', 'emails', 'state'])
                           ->where('comid = :id', [':id' => $id])->asArray()->one();
                if(!is_null($company)){
                    return Tool::showRes([0, '获取成功'], $company);
                }else{
                    return Tool::showRes(ErrMap::getError(10010));
                };
            }
        }

        return Tool::showRes(ErrMap::getError(10005));
    }


    /*初始化密码*/
    public function actionInitPwd()
    {
        // echo "init";
        if(Yii::$app->request->isPost){
            // P($this->post);
            $admin = new Admin;

            if($admin->initPwd($this->post, $this->post['Admin']['comid'])){
                $backInfo = [0, $this->post['Admin']['companyname'] . ' - 初始化密码成功'];//返回信息
            }else{
                if($admin->hasErrors()){
                    $backInfo = ErrMap::getError(10005);//返回信息
                }
            }

            if(!isset($backInfo)){
                $backInfo = ErrMap::getError(10005);//返回信息
            }
            if(!isset($exception)){
                $exception = '';//异常信息
            }
            //操作日志
            if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo, $this->userInfo), $exception) ) != 'boolean'){
                return $res;
            };
        }
    }

    /*充值*/
    public function actionTopUp()
    {
        // echo "topup";
        if(Yii::$app->request->isPost){
            // P($this->post);
            $transaction = Yii::$app->db->beginTransaction();//事物处理
            $pass = true;
            try{
                /*添加记录*/
                $companyAccountRecord = new CompanyAccountRecord;
                $this->post['CompanyAccountRecord']['flag'] = 1;
                $this->post['CompanyAccountRecord']['paymode'] = 1;
                $this->post['CompanyAccountRecord']['way'] = 2;
                // P($this->post);
                if(!($amount = $companyAccountRecord->addRecord($this->post))){
                    if($companyAccountRecord->hasErrors()){
                        $backInfo = ErrMap::getError(10005);//返回信息
                        $exception = $companyAccountRecord->getErrors();//异常信息
                    }
                    $pass = false;
                }

                /*增加总金额*/
                if($pass){
                    if(!Company::updateAllCounters(['account' => $amount], 'comid = :comid', [':comid' => $this->post['CompanyAccountRecord']['comid']])){
                        $pass = false;
                    }
                }

                if($pass){
                    $backInfo = [0, $this->post['CompanyAccountRecord']['companyname'] . '充值成功'];//返回信息
                    $transaction->commit();
                }
            }catch(\Exception $exception){
                $transaction->rollback();
            };

            if(!isset($backInfo)){
                $backInfo = ErrMap::getError(10005);//返回信息
            }
            if(!isset($exception)){
                $exception = '';//异常信息
            }
            //操作日志
            if(gettype( $res = OperationLog::addLog($this->operationLogArgs($backInfo), $exception) ) != 'boolean'){
                return $res;
            };
        }
    }


    /*校验联系人*/
    private function checkContact()
    {
        if(isset($this->post['Company']['contacts']) and 
            isset($this->post['Company']['phones']) and 
            isset($this->post['Company']['emails']) and 
            count($this->post['Company']['contacts']) == count($this->post['Company']['phones']) and 
            count($this->post['Company']['contacts']) == count($this->post['Company']['emails'])){
            $this->post['Company']['contacts'] = implode(',', $this->post['Company']['contacts']);
            $this->post['Company']['phones'] = implode(',', $this->post['Company']['phones']);
            $this->post['Company']['emails'] = implode(',', $this->post['Company']['emails']);
        }
    }

    /*
    检查营业执照号码 是否存在
    $businessLicense    营业执照号码
    */
    // private function checkRepeatBusinessLicense($businessLicense)
    // {
    //     $res = true;//默认存在
    //     if(!empty($businessLicense)){
    //         $company = Company::find()->where('business_license = :license', [':license' => $businessLicense])->one();
    //         $res = $company?true:false;
    //     };
    //     return $res;
    // }

    /*微信公众号账号列表*/
    public function actionWechatList()
    {
        if(isset($this->get['comid'])){
            $comid = intval($this->get['comid']?$this->get['comid']:'');

            if(!empty($comid)){
                $com_id = $this->getComIdByComid($comid);
                // P($com_id);
                if(isset($this->get['page'])){
                    $currPage = intval($this->get['page']?$this->get['page']:1);
                }else{
                    $currPage = 1;
                }
                $pageSize = Tool::getPageSize();

                $companyWechat = new CompanyWechat;
                $count = $companyWechat::find()->where('com_id = :com_id', [':com_id' => $com_id])->count();
                $companyWechatList = $companyWechat::find()
                                        ->select(['wid', 'appid', 'appsecret', 'isdefault', 'add_time'])
                                        ->where('com_id = :com_id', [':com_id' => $com_id])
                                        ->offset($pageSize*($currPage-1))->limit($pageSize)
                                        ->asArray()->all();
                $res = array(
                    'list' => $companyWechatList,
                    'pageInfo' => array(
                        'count' => intval($count),
                        'currPage' => $currPage,
                        'pageSize' => $pageSize,
                    ),
                );
                return Tool::showRes([0, '获取成功'], $res);
            }
        }
        return Tool::showRes(ErrMap::getError(10005));
    }

    /*添加微信公众号账号*/
    public function actionAddWechat()
    {
        P($this->post);
    }

    /*修改微信公众号账号*/
    public function actionModifyWechat()
    {
        P($this->post);
    }


    
}
